package com.example.freeengine.wallpaper.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.bumptech.glide.Glide;
import com.example.freeengine.wallpaper.constants.WallPaperConstant;
import com.example.freeengine.wallpaper.constants.WallPaperUpdateStrategy;
import com.example.freeengine.wallpaper.fragment.cyclerefresh.AlbumInfo;
import com.example.freeengine.wallpaper.fragment.everydayrefresh.picturesource.BingPictureSource;
import com.example.freeengine.wallpaper.network.VolleyCallback;
import com.example.freeengine.wallpaper.persistence.entity.WallPaperCycleRefreshAlbum;
import com.example.freeengine.wallpaper.persistence.entity.WallPaperCycleRefreshAlbumItem;
import com.example.freeengine.wallpaper.persistence.repository.WallPaperCycleRefreshRepository;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TreeSet;
import java.util.concurrent.ExecutionException;


/**
 * @author Terry Deng
 */
public class WallPaperViewModel extends ViewModel {

    private static final String TAG = WallPaperViewModel.class.getSimpleName();

    // 列表中照片删除
    public MutableLiveData<Integer> pictureListDataChange = new MutableLiveData<>(0);

    // 列表中照片删除
    public MutableLiveData<Integer> everydayRefreshHistoryDataChange = new MutableLiveData<>(0);

    // 修改 循环刷新的album id
    public MutableLiveData<Long> cycleRefreshAlbumChange = new MutableLiveData<>(-1L);

    public List<PictureInfo> getWallPaperTakePictures(String wallPaperTakePicturePath){
        List<PictureInfo> pictureInfos = new ArrayList<>();
        Log.i("wallpaper path", "getWallPaperTakePictures: " + wallPaperTakePicturePath);
        File imagesDir = new File(wallPaperTakePicturePath);
        if (!imagesDir.exists()) {
            return pictureInfos;
        }

        PictureInfo pictureInfo;
        File[] files = imagesDir.listFiles();
        if (files != null && files.length > 0){
            for (File f : files){
                pictureInfo = new PictureInfo();
                if (f.isFile()){
                    pictureInfo.setPath(f.getAbsolutePath());
                    pictureInfos.add(pictureInfo);
                }
            }
        }
        return pictureInfos;
    }

    public File createImageFile(File storageDir) throws IOException {
        // Create an image file name
        Log.i("TAG", "createImageFile: " + storageDir);
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_" + ".jpeg";

        if (!storageDir.exists()){
            storageDir.mkdirs();
        }

        File image = new File(storageDir, imageFileName);
        if (!image.exists()){
            image.createNewFile();
        }
        // Save a file: path for use with ACTION_VIEW intents
        return image;
    }

    public File createImageFile(String storageDirPath) throws IOException {
        // Create an image file name
        Log.i("TAG", "createImageFile: " + storageDirPath);

        File file = new File(storageDirPath);
        if (!file.exists()){
            file.mkdirs();
        }
        return createImageFile(file);
    }

    public List<AlbumInfo> getAlbumInfoList(List<WallPaperCycleRefreshAlbum> wallPaperCycleRefreshAlbumList, WallPaperCycleRefreshRepository wallPaperCycleRefreshRepository){
        List<AlbumInfo> albumInfoList = new ArrayList<>();
        if (wallPaperCycleRefreshAlbumList != null && wallPaperCycleRefreshAlbumList.size() > 0){
            AlbumInfo albumInfo;
            for(WallPaperCycleRefreshAlbum wpcra : wallPaperCycleRefreshAlbumList){
                albumInfo = new AlbumInfo(wpcra);

                List<WallPaperCycleRefreshAlbumItem> items = null;
                try {
                    items = wallPaperCycleRefreshRepository.findAllByAlbumId(wpcra.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                albumInfo.setName(wpcra.getName());
                if (items != null && items.size() > 0){
                    albumInfo.setItemCount(items.size());
                    albumInfo.setPreviewPath(items.get(0).getPicturePath());
                }
                albumInfoList.add(albumInfo);
            }
        }
        return albumInfoList;
    }

    public List<AlbumInfo> getAlbumInfoList(List<WallPaperCycleRefreshAlbum> wallPaperCycleRefreshAlbumList,
                                            WallPaperCycleRefreshRepository wallPaperCycleRefreshRepository,
                                            Long usingId){
        List<AlbumInfo> albumInfoList = new ArrayList<>();
        if (wallPaperCycleRefreshAlbumList != null && wallPaperCycleRefreshAlbumList.size() > 0){
            AlbumInfo albumInfo;
            for(WallPaperCycleRefreshAlbum wpcra : wallPaperCycleRefreshAlbumList){
                albumInfo = new AlbumInfo(wpcra);

                List<WallPaperCycleRefreshAlbumItem> items = null;
                try {
                    items = wallPaperCycleRefreshRepository.findAllByAlbumId(wpcra.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                albumInfo.setName(wpcra.getName());
                albumInfo.setUsing(wpcra.getId().equals(usingId));
                if (items != null && items.size() > 0){
                    albumInfo.setItemCount(items.size());
                    albumInfo.setPreviewPath(items.get(0).getPicturePath());
                }
                albumInfoList.add(albumInfo);
            }
        }
        return albumInfoList;
    }

    public List<WallPaperCycleRefreshAlbumItem> createWallPaperCycleRefreshAlbumItems(List<String> imagesPath, Long albumId){

        List<WallPaperCycleRefreshAlbumItem> wallPaperCycleRefreshAlbumItemList = new ArrayList<>();
        WallPaperCycleRefreshAlbumItem wallPaperCycleRefreshAlbumItem;
        for (String p : imagesPath){
            wallPaperCycleRefreshAlbumItem = new WallPaperCycleRefreshAlbumItem();
            wallPaperCycleRefreshAlbumItem.setAlbumId(albumId);
            wallPaperCycleRefreshAlbumItem.setPicturePath(p);

            wallPaperCycleRefreshAlbumItem.setRefreshOrder(0);

            wallPaperCycleRefreshAlbumItemList.add(wallPaperCycleRefreshAlbumItem);
        }
        return wallPaperCycleRefreshAlbumItemList;

    }

    public List<PictureInfo> getEverydayRefreshHistoryPictures(String Path){
        List<PictureInfo> pictureInfos = new ArrayList<>();

        TreeSet<File> fileTreeSet = new TreeSet<>(new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                if (o1.lastModified() - o2.lastModified() == 0) return 0;
                if (o1.lastModified() - o2.lastModified() < 0) return 1;

                return -1;
            }
        });

        Log.i("wallpaper path", "getWallPaperTakePictures: " + Path);
        File imagesDir = new File(Path);
        if (!imagesDir.exists()) {
            return pictureInfos;
        }

        File[] files = imagesDir.listFiles();
        if (files != null && files.length > 0){
            for (File f : files){
                if (f.isFile()){
                    fileTreeSet.add(f);
                }
            }
        }

        fileTreeSet.forEach(f -> {
            PictureInfo pictureInfo = new PictureInfo();
            pictureInfo.setPath(f.getAbsolutePath());
            pictureInfos.add(pictureInfo);

        });

        return pictureInfos;
    }

    public void saveEverydayRefreshPicture(Context context, String path){
        BingPictureSource.generatePictureUrl(context, new VolleyCallback() {
            @Override
            public void onSuccess(String newRequest) {

                String wallPaperEveryDayRefreshCurrentFlag = getWallPaperEveryDayRefreshCurrentFlag(context);
                if (wallPaperEveryDayRefreshCurrentFlag.equals(newRequest)){
                    // 如果已经下载过了，不再下载
                    Log.i(TAG, "onSuccess: " + "having download: " + newRequest);
                    return;
                }
                try {
                    // 当前图片
                    File file = Glide.with(context).downloadOnly().load(newRequest).submit().get();
                    File dstDir = new File(path);
                    if (!dstDir.exists()) {
                        dstDir.mkdirs();
                    }
                    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
                    String imageFileName = "JPEG_" + timeStamp + "_" + ".jpeg";
                    File dstFile = new File(dstDir, imageFileName);
                    if (!dstFile.exists()) {
                        dstFile.createNewFile();
                    }
                    try (InputStream is = new FileInputStream(file);
                         OutputStream os = new FileOutputStream(dstFile)) {
                        byte[] fData = new byte[1024];
                        int len = 0;
                        while ((len = is.read(fData)) > 0) {
                            os.write(fData, 0, len);
                        }
                        setWallPaperEveryDayRefreshCurrentFlag(context, newRequest);
                    }
                } catch (ExecutionException | IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public String getWallPaperEveryDayRefreshCurrentFlag(Context context){
        SharedPreferences sharedPreferences = context.getSharedPreferences(WallPaperConstant.SHP_WALLPAPER_FILE_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(WallPaperConstant.KEY_SHP_WALLPAPER_EVERYDATREFRESH_CURRENT_FLAG, "0");
    }
    public void setWallPaperEveryDayRefreshCurrentFlag(Context context, String url){
        SharedPreferences sharedPreferences = context.getSharedPreferences(WallPaperConstant.SHP_WALLPAPER_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(WallPaperConstant.KEY_SHP_WALLPAPER_EVERYDATREFRESH_CURRENT_FLAG, url);
        edit.apply();
    }

    public void setWallPaperUpdateStrategyInfo(WallPaperUpdateStrategy wallPaperUpdateStrategy, Context context, String targetFlag){
        SharedPreferences sharedPreferences = context.getSharedPreferences(WallPaperConstant.SHP_WALLPAPER_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();

        edit.putString(WallPaperConstant.KEY_SHP_WALLPAPER_CURRENT_STRATEGY, wallPaperUpdateStrategy.name());
        if (wallPaperUpdateStrategy == WallPaperUpdateStrategy.FROM_CYCLEREFRESH){
            edit.putLong(WallPaperConstant.KEY_SHP_WALLPAPER_CURRENT_CYCLEREFRESH_ALBUM_INFO, Long.parseLong(targetFlag));
        }else if (wallPaperUpdateStrategy == WallPaperUpdateStrategy.FROM_EVERYDAY){
            edit.putString(WallPaperConstant.KEY_SHP_WALLPAPER_CURRENT_EVERYDAYREFRESH_SOURCE_INFO, targetFlag);
        }

        edit.apply();
    }

    public String getWallPaperUpdateStrategyInfo(Context context){
        SharedPreferences sharedPreferences = context.getSharedPreferences(WallPaperConstant.SHP_WALLPAPER_FILE_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(WallPaperConstant.KEY_SHP_WALLPAPER_CURRENT_STRATEGY, WallPaperUpdateStrategy.NOT_SET.name());
    }

    public Long getWallPaperUpdateStrategyCycleRefreshInfo(Context context){
        SharedPreferences sharedPreferences = context.getSharedPreferences(WallPaperConstant.SHP_WALLPAPER_FILE_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getLong(WallPaperConstant.KEY_SHP_WALLPAPER_CURRENT_CYCLEREFRESH_ALBUM_INFO, -1L);
    }


    public LiveData<List<WallPaperCycleRefreshAlbum>> getAlbumList(WallPaperCycleRefreshRepository wallPaperCycleRefreshRepository){
        return wallPaperCycleRefreshRepository.findAlbumAll();
    }
    public LiveData<List<WallPaperCycleRefreshAlbumItem>> getAlbumItemList(WallPaperCycleRefreshRepository wallPaperCycleRefreshRepository, Long albumId){
        return wallPaperCycleRefreshRepository.findAllByAlbumIdLiveData(albumId);
    }

    public LiveData<Long> getCycleRefreshAlbumChange() {
        return cycleRefreshAlbumChange;
    }
    public void setCycleRefreshAlbumChange(Long id) {
        cycleRefreshAlbumChange.setValue(id);
    }

    public LiveData<Integer> getEverydayRefreshHistoryDataChange(){
        return everydayRefreshHistoryDataChange;
    }

    public void setEverydayRefreshHistoryDataChange(Integer change){
        everydayRefreshHistoryDataChange.setValue(change);
    }

    public Long getWallPaperCycleRefreshFrequency(Context context){
        SharedPreferences sharedPreferences = context.getSharedPreferences(WallPaperConstant.SHP_WALLPAPER_FILE_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getLong(WallPaperConstant.KEY_SHP_WALLPAPER_CURRENT_CYCLEREFRESH_ALBUM_FREQUENCY, 1L);
    }
    public void setWallPaperWallPaperCycleRefreshFrequency(Context context, Long frequency){
        SharedPreferences sharedPreferences = context.getSharedPreferences(WallPaperConstant.SHP_WALLPAPER_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putLong(WallPaperConstant.KEY_SHP_WALLPAPER_CURRENT_CYCLEREFRESH_ALBUM_FREQUENCY, frequency);
        edit.apply();
    }

    public void setCycleRefreshAlbumItemInfo(Context context, Long id){
        SharedPreferences sharedPreferences = context.getSharedPreferences(WallPaperConstant.SHP_WALLPAPER_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putLong(WallPaperConstant.KEY_SHP_WALLPAPER_CURRENT_PICTURE_INFO, id);
        edit.apply();
    }

    public String getWallPaperAlarmWakeupTime(Context context){
        SharedPreferences sharedPreferences = context.getSharedPreferences(WallPaperConstant.SHP_WALLPAPER_FILE_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(WallPaperConstant.KEY_ALARM_WAKEUP_TIME, "--");
    }
}